package com.rxnetwork.sample.module.home.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.rxnetwork.bus.RxBus;
import com.rxnetwork.bus.RxBusCallBack;
import com.rxnetwork.sample.R;
import com.rxnetwork.sample.amshook.AMSHookUtil;
import com.rxnetwork.sample.api.Api;
import com.rxnetwork.sample.api.ApiInterface;
import com.rxnetwork.sample.model.ListModel;
import com.rxnetwork.sample.module.home.adapter.MainAdapter;
import com.rxnetwork.sample.mvp.toolbar.BaseTopBarActivity;
import com.rxnetwork.sample.test.TestActivity;
import com.rxnetwork.sample.utils.network.AppNetWorkListener;
import com.rxnetwork.sample.utils.network.AppNetWorkManager;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseTopBarActivity
        implements AppNetWorkListener<List<ListModel>>, SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout swipeRefreshLayout;
    private MainAdapter adapter;

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void initViewsAndEvents() {
        AMSHookUtil.hookStartActivity(this);

        getTopBarLayout().getLeftImg().setVisibility(View.GONE);
        setTopBarLayoutColor(getResources().getColor(R.color.colorAccent));
        getTopBarLayout().getRightTv().setVisibility(View.VISIBLE);
        getTopBarLayout().getRightTv().setText("fragment");
        getTopBarLayout().getRightTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                TestMVPFragment testFragment = new TestMVPFragment();
//                getSupportFragmentManager().beginTransaction().replace(R.id.test_fragment,
//                        testFragment, TestMVPFragment.class.getName())
//                        .addToBackStack(null)
//                        .commitAllowingStateLoss();
                startActivity(new Intent(MainActivity.this, TestActivity.class));
//                startActivity(new Intent(MainActivity.this, IndexActivity.class));
            }
        });

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        adapter = new MainAdapter(this, new ArrayList<ListModel>());
        adapter.setItemClickListener(new MainAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                startActivity(intent);
                Toast.makeText(MainActivity.this, "onItemClick" + position, Toast.LENGTH_SHORT).show();
            }
        });
        recyclerView.setAdapter(adapter);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                onRefresh();
            }
        });

        RxBus.getInstance().toSubscription("rxbusTag", new RxBusCallBack<String>() {
            @Override
            public void onNext(String data) {
                Toast.makeText(MainActivity.this, "RxBus数据：" + data, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable throwable) {
                Toast.makeText(MainActivity.this, "RxBus error：" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        swipeRefreshLayout.setRefreshing(true);
        AppNetWorkManager.getInstance().clearSubscription();
    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_main;
    }

    @Override
    protected CharSequence getTopTitle() {
        return "首页";
    }

    @Override
    public void onRefresh() {
        AppNetWorkManager
                .getInstance()
                .setBaseUrl(Api.ZL_BASE_API)
                .getApi(AppNetWorkManager.observable(ApiInterface.class).getList("daily", 20, 0), this);

        Map<String, String> mapsTest2 = new HashMap<>();
        mapsTest2.put("cate", "lol");
        mapsTest2.put("pageno", "1");
        mapsTest2.put("pagenum", "20");
        test2(mapsTest2);

        //多文件上传和form表单数据
        Map<String, String> maps = new HashMap<>();
        maps.put("userName", "xiaocodeTest");
        maps.put("serviceIP", "123456");
        List<File> listFile = new ArrayList<>();
        listFile.add(getImageFromAssetsFile("aaa.png"));
        listFile.add(getImageFromAssetsFile("bbb.png"));
        AppNetWorkManager
                .getInstance()
                .setBaseUrl(Api.LOCAL_HOST)
                .setUploadFiles("fileKey", listFile, maps)
                .getApi(AppNetWorkManager.observable(ApiInterface.class).upload(AppNetWorkManager.getMultipartBody()), new AppNetWorkListener<Object>() {
                    @Override
                    public void onNetWorkError(Throwable e) {
                        Toast.makeText(getApplicationContext(), "上传图片失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNetWorkSuccess(Object data) {
                        Toast.makeText(getApplicationContext(), "上传图片成功" + data, Toast.LENGTH_SHORT).show();
                    }
                });

        Map<String, String> test4Map = new HashMap<>();
        test4Map.put("phoneNum", "15914020670");
        test4(test4Map);
    }

    public void test2(Map<String, String> map) {
        AppNetWorkManager
                .getInstance()
                .setBaseUrl(Api.TEST_URL)
                .getApi(AppNetWorkManager.observable(ApiInterface.class).getTest2String(map), new AppNetWorkListener<Object>() {
                    @Override
                    public void onNetWorkError(Throwable e) {
                        Toast.makeText(getApplicationContext(), "请求失败-------String", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNetWorkSuccess(Object data) {
                        Toast.makeText(getApplicationContext(), "请求成功-------String", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public void test4(Map<String, String> map) {
        AppNetWorkManager
                .getInstance()
                .setBaseUrl(Api.TEST2_URL)
                .getApi(AppNetWorkManager.observable(ApiInterface.class).getTest4String(map), new AppNetWorkListener<Object>() {
                    @Override
                    public void onNetWorkError(Throwable e) {
                        Toast.makeText(getApplicationContext(), "请求失败4-------String", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNetWorkSuccess(Object data) {
                        Toast.makeText(getApplicationContext(), "请求成功4-------String", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onNetWorkError(Throwable e) {
        swipeRefreshLayout.setRefreshing(false);
        Toast.makeText(getApplicationContext(), "net work error", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNetWorkSuccess(List<ListModel> data) {
        swipeRefreshLayout.setRefreshing(false);
        adapter.clear();
        adapter.addAll(data);
    }

    /**
     * 从Assets中读取图片
     */
    private File getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File file = new File(Environment.getExternalStorageDirectory(), fileName);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            image.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //这是解绑定指定的key
        RxBus.getInstance().unregister("rxbusTag");
        //解除所有的key
        RxBus.getInstance().unregisterAll();
    }
}
